//
//  AppDelegate.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/11/14.
//

import UIKit
import CoreData
import SnapKit
import RxSwift
import RxCocoa
import RxRelay
import SnapKitExtend
import RxGesture
import IQKeyboardManagerSwift
import Reachability

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var blockRotation = Bool()
    let reachability = try! Reachability()
    var timer: Timer!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        Thread.sleep(forTimeInterval: 3.0) // 设置启动页面时间
        // Override point for customization after application launch.
        FilesManager.shared.clearCaches()
        IQKeyboardManager.shared.enable = true

        setupReachability()

        window = UIWindow(frame: UIScreen.main.bounds)
        setupUI()
        window?.rootViewController?.view.backgroundColor = .white
        window?.makeKeyAndVisible()
        return true
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
    }

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if blockRotation {
//            return .allButUpsideDown //支持横竖屏旋转
            return .landscapeLeft //强制横屏时这里可保持一个方向
        }
        return .portrait
    }

    // MARK: - Setup

    func setupUI() {
        let token = UserDefaults.standard.string(forKey: SafetyToken)
        if token == nil {
            window?.rootViewController = UINavigationController(rootViewController: LoginVC())
            disNoti()
        } else {
            setupMain()
        }
    }

    func setupMain() {
        createNoti()
//        WSManager.shared.setup()
        let role = UserDefaults.standard.string(forKey: SafetyUserRole)
        if (role == UserRole.Engineer.rawValue) {
            window?.rootViewController = EngineerHomeVC()
        } else if (role == UserRole.SecurityGuard.rawValue || role == UserRole.Cleaning.rawValue) {
            window?.rootViewController = UINavigationController(rootViewController: SecurityHomeVC())
        } else {
            window?.rootViewController = MainTabVC()
        }
    }
    
    func setupReachability() {
        reachability.whenReachable = { reach in
            if reach.connection == .wifi {
                print("Reachable via WiFi")
            } else {
                print("Reachable via Cellular")
            }
        }
        reachability.whenUnreachable = { _ in
            Utils.app.window?.showToast(witMsg: "请检查网络连接是否正常")
        }
        
        do {
            try reachability.startNotifier()
        } catch {
            print("Unable to start notifier")
        }
    }
    
    func createNoti() {
        disNoti()
        timer = Timer.scheduledTimer(timeInterval: 180, target:self, selector: #selector(fetchNoti), userInfo: nil, repeats: true)
        fetchNoti()
    }
    
    func disNoti() {
        if (timer != nil) {
            timer.invalidate()
            timer = nil
        }
    }
    
    @objc func fetchNoti() {
        API.getNoticeOwner() { responseModel in
            print("getNoticeOwner", responseModel)
            DispatchQueue.main.async {
                if let m = responseModel.model, m.status == 1 {
                    if let info = m.info {
                        Utils.showBanner(info)
                    }
                }
            }
        }
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "SBSafetyApp")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext() {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    // 开启通知
    func addNoti() {
//        //开启通知
//        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (status, err) in
//            if !status {
//                print("用户不同意授权通知权限")
////                guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
////                if UIApplication.shared.canOpenURL(url) {
////                    UIApplication.shared.open(url, completionHandler: nil)
////                }
//                return
//            }
//        }
//        UNUserNotificationCenter.current().delegate = self
    }
    
//    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
//        UIApplication.shared.applicationIconBadgeNumber = 0
//    }
}

